layui.define(['global', 'layer'], function (exports) {
    var layer = layui.layer;
    var config = layui.global;
    var $ = layui.$;
    var popupRightIndex, popupCenterIndex, popupCenterParam;

    const reqInst = axios.create({
        baseURL: config.baseServer + '/jsdata',
        timeout: 6000,
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }
    });

    // 添加请求前置拦截器
    reqInst.interceptors.request.use(config => {
        // Do something before request is sent
        // layer.load(1);
        return config;
    }, err => {
        console.log('request before =>', err);
        return Promise.reject(err);
    });

    // 添加响应后置拦截器
    reqInst.interceptors.response.use(response => {
        // Do something with response data
        // console.log('success =>', response);
        if (response.status === 200) {
            const r = response.data
            if (r.code !== undefined) {
                if (r.code === 0) {
                    return r;
                } else {
                    layer.msg(response.data.msg || '服务器未知错误，请刷新', {icon: 2, time: 3000})
                    return Promise.reject(response);
                }
            } else {
                // console.log('没有code，才返回 =>', response);
                return Promise.resolve(response);
            }
        } else {
            layer.msg('服务器响应失败，请稍后重试', {icon: 2, time: 3000})
            return Promise.reject(response);
        }
    }, function (error) {
        // Do something with response error
        layer.closeAll('loading');
        console.log('error =>', error);
        layer.msg('请求失败，请稍后重试', {icon: 5, time: 2000})

        return Promise.reject(error);
    });

    var admin = {
        // 中间弹出
        popupCenter: function (param) {
            param.id = param.id ? param.id : 'ASSIT_POPUP_CENTER';
            popupCenterParam = param;
            popupCenterIndex = admin.open(param);
            return popupCenterIndex;
        },
        // 关闭中间弹出并且触发finish回调
        finishPopupCenter: function () {
            layer.close(popupCenterIndex);
            popupCenterParam.finish ? popupCenterParam.finish() : '';
        },
        // 关闭中间弹出
        closePopupCenter: function () {
            layer.close(popupCenterIndex);
        },
        // 封装layer.open
        open: function (param) {
            var sCallBack = param.success;
            param.type = 1;
            param.area = param.area ? param.area : '450px';
            param.offset = param.offset ? param.offset : '120px';
            param.resize ? param.resize : false;
            param.shade ? param.shade : .2;
            param.success = function (layero, index) {
                sCallBack ? sCallBack(layero, index) : '';
                $(layero).children('.layui-layer-content').load(param.path);
            };
            return layer.open(param);
        },
        req: function (url, method = 'get', loading = true, config = {}) { // params, data
            var cfg;
            if (config && typeof object === 'object') {
                cfg = config;
            } else {
                cfg = new Object();
            }

            cfg.url = url;
            cfg.method = method;
            // if (loading) {
            //     layer.load(1);
            // }
            return reqInst.request(cfg);
        },
        delete: function (url, params = {}) {
            return reqInst.delete(url, {params})
        },
        post: function (url, data, config = {}) {
            return reqInst.post(url, data, config)
        },
        // 获取模型明细中的类型数据
        fetchMDTypeData: async function () {
            const o1 = config.getCache(config.PRO_TYPE_KEY)
            const o2 = config.getCache(config.COL_TYPE_KEY)

            if (o1 && o1.length > 0 && o2 && o2.length > 0) {
                // console.log('read from cache =>')
                return Promise.resolve({
                    proTypeList: o1,
                    colTypeList: o2
                })
                // initSelector(o1, $('#proType'))
                // initSelector(o2, $('#colType'))
            } else {
                // 后台获取
                const r = await admin.req('/model/detail/types/list');
                // console.log(r)
                if (r.code === 0) {
                    const proList = r.data.proTypeList.map(o => {
                        var oo = {}
                        oo.id = o.id
                        oo.name = o.name
                        return oo
                    })

                    const colList = r.data.colTypeList.map(o => {
                        var oo = {}
                        oo.id = o.id
                        oo.name = o.name
                        return oo
                    })

                    config.putCache(config.PRO_TYPE_KEY, proList)
                    config.putCache(config.COL_TYPE_KEY, colList)

                    return Promise.resolve({
                        proTypeList: proList,
                        colTypeList: colList
                    })
                } else {
                    layer.msg('加载类型列表失败', {anim: 1, icon: 5})
                }

                return Promise.resolve({})
            }
        },
        initSelector: function initSelector(list, el) {
            if (list === null || list.length < 1) {
                return
            }

            $.each(list, (index, item) => {
                el.append("<option value='" + item.id + "'>" + item.name + "</option>")
            })
        },
        // 判断是否为json
        parseJSON: function (str) {
            if (typeof str == 'string') {
                try {
                    var obj = JSON.parse(str);
                    if (typeof obj == 'object' && obj) {
                        return obj;
                    }
                } catch (e) {
                }
            }
        }

        // // 封装ajax请求，返回数据类型为json
        // req: function (url, data, success, method, noHeaderToken) {
        //     if ('put' == method.toLowerCase()) {
        //         method = 'PUT';
        //     } else if ('delete' == method.toLowerCase()) {
        //         method = 'DELETE';
        //     }
        //     //add by owen ajax 执行前置处理器  
        //     admin.ajax({
        //         url: config.base_server + url,
        //         data: data,
        //         type: method,
        //         dataType: 'json',
        //         contentType: "application/json",
        //         success: success,
        //         beforeSend: function (xhr) {
        //             if (!noHeaderToken) {
        //                 let token = config.getToken();
        //                 if (token) {
        //                     xhr.setRequestHeader('Authorization', 'Bearer ' + token.access_token);
        //                 }
        //             }
        //             let isolationVersion = config.isolationVersion;
        //             if (isolationVersion) {
        //                 xhr.setRequestHeader('z-l-t-version', isolationVersion);
        //             }
        //         }
        //     });
        // },

        // // 封装ajax请求
        // ajax: function (param) {
        //     var successCallback = param.success;
        //     param.success = function (result, status, xhr) {
        //         // 判断登录过期和没有权限
        //         var jsonRs;
        //         if ('json' == param.dataType.toLowerCase()) {
        //             jsonRs = result;
        //         } else if ('html' == param.dataType.toLowerCase() || 'text' == param.dataType.toLowerCase()) {
        //             jsonRs = admin.parseJSON(result);
        //         }
        //         if (jsonRs) {
        //             if (jsonRs.code == 401) {
        //                 config.removeToken();
        //                 layer.msg('登录过期', {icon: 2, time: 1500}, function () {
        //                     location.replace('/login.html');
        //                 }, 1000);
        //                 return;
        //             } else if (jsonRs.code == 403) {
        //                 layer.msg('没有权限', {icon: 2});
        //                 layer.closeAll('loading');
        //                 return;
        //             } else if (jsonRs.code === 500) {
        //                 layer.closeAll('loading');
        //                 if (jsonRs.data) {
        //                     let r = admin.parseJSON(jsonRs.data);
        //                     // 弹出后台自己的提示信息
        //                     if (r.resp_msg) {
        //                         layer.msg(r.resp_msg, {icon: 2, time: 1500});
        //                     }
        //                 }
        //                 return;
        //             }
        //         }
        //         successCallback(result, status, xhr);
        //     };
        //     param.error = function (xhr) {
        //         param.success({code: xhr.status, data: xhr.responseText});
        //     };
        //     //发送同步ajax请求
        //     param.async = false;
        //     //console.log(param);
        //     $.ajax(param);
        // },
        // 判断是否有权限
        // hasPerm: function (auth) {
        //     var permissions = admin.getTempData("permissions");
        //     if (permissions){
        //         for (var i = 0; i < permissions.length; i++) {
        //             if (auth == permissions[i]) {
        //                 return true;
        //             }
        //         }
        //     }
        //     return false;
        // },
    };

    exports('admin', admin);
});
